<?php
namespace app\api\controller;
use app\common\controller\CommonApi;
use Pay\Pay;
use think\Db;
/**
 * 需求模块
 */
class Need extends CommonApi{

    /**
     * [发布需求]
     * @return [type] [description]
     */
    public function issue(){
        $validate = validate('Need');  
        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        if(strtotime($this->post['end_time']) < time()){
            $this->apiReturn(0,'截止时间不得小于当前时间');
        }
        //需求图片
        if(isset($this->post['image']) && $this->post['image'] !== ''){
            $image = explode(',',$this->post['image']);
            if(count($image) > 9){
                $this->apiReturn(0,'需求图片最多不超过9张');
            }
        }

        //有偿服务是需要支付金额的
        if($this->post['type'] == 1){
            if(!isset($this->post['budget']) || floatval($this->post['budget']) <= 0){
                $this->apiReturn(0,'请输入预算金额');
            }

            if(!isset($this->post['pay_price']) || floatval($this->post['pay_price']) <= 0){
                $this->apiReturn(0,'请输入定金金额');
            }
            if(!isset($this->post['unit']) || trim($this->post['unit']) == ''){
                $this->apiReturn(0,'请输入预算金额单位');
            }

            $min_issue_price = db('web_config')->where('key','need_min_price')->value('value');
            if(floatval($this->post['pay_price']) < floatval($min_issue_price)){
                $this->apiReturn(0,'最低金额不得小于'.$min_issue_price);
            }
        }
        
        $this->post['end_time'] = strtotime($this->post['end_time']);
        $this->post['user_id'] = UID;
        if(!model('common/need')->allowField(true)->save($this->post)){
            $this->apiReturn(0,'发布需求失败');
        }

       
        $this->apiReturn(1,'发布需求成功',model('common/need')->id);
    } 

    /**
     * [需求接单]
     * @return [type] [description]
     */
    public function  orderNeed(){
        if(!isset($this->post['id']) || intval($this->post['id']) <= 0){
            $this->apiReturn(0,'参数id丢失');
        }

        $model = model('common/need')->get(intval($this->post['id']));
        if(is_null($model) || $model['status'] == 0){
            $this->apiReturn(0,'该需求不存在或已被删除');
        }

        if($model['end_time'] < time()){
            $this->apiReturn(0,'该需求已经过期');
        }

        if($model['user_id'] == UID){
            $this->apiReturn(0,'不能接自己发布的需求');
        }
        //查看是否接单
        if(db('need_apply')->where('foreign_key',intval($this->post['id']))->where('apply_user',UID)->find()){
            $this->apiReturn(0,'该需求已经接单');
        }

        db()->startTrans();
        if(!db('need_apply')->insert(['apply_user'=>UID,'foreign_key'=>intval($this->post['id']),'apply_time'=>time(),'need_type'=>$model['type']])){
            db()->rollback();
            $this->apiReturn(0,'添加报名记录失败');
        }

        if(!$model->setInc('apply_num')){
            db()->rollback();
            $this->apiReturn(0,'添加报名名额失败');
        }
        db()->commit();
        //极光推送
        if($model['hint']){
            $res = JPush($model['user_id'],$mdoel['title'].'被人接单');
        }
        $this->apiReturn(1,'申请成功');
    }

    //删除需求
    public function delNeed(){
        if(!isset($this->post['id']) || intval($this->post['id']) <= 0){
            $this->apiReturn(0,'参数id丢失');
        }
        $model = model('common/need')->where('user_id',UID)->where('id',intval($this->post['id']))->where('status',1)->find();
        if(is_null($model)){
            $this->apiReturn(0,'该需求不存在或已被删除');
        }
        if(!$model->save(['status' => 0])){
            $this->apiReturn(0,'删除失败，请稍后再试');
        }
        $this->apiReturn(1,'删除成功');
    }
   


    /**
     * [selectApply 选中申请者]
     * @return [type] [description]
     */
    public function selectApply(){
        $validate  = new \think\validate([
            'apply_user' => 'require',
            'id' => 'require',
            'pay_type' => 'in:0,1,2'
        ],[
            'apply_user.require' => '报名者id丢失',
            'id.require' => '需求id丢失',
            'pay_type.in' => '支付方式错误'
        ]);
        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        $need_info = db('need')->where('id',intval($this->post['id']))->where('status',1)->find();

        if(is_null($need_info)){
            $this->apiReturn(0,'该需求不存在或已被删除');
        }

        if($need_info['user_id'] != UID){
            $this->apiReturn(0,'信息有误');
        }

        $apply_info = model('common/need_apply')->where('apply_user',intval($this->post['apply_user']))->where('foreign_key',intval($this->post['id']))->find();

        if(is_null($apply_info)){
            $this->apiReturn(0,'该用户已取消报名');
        }

        if($apply_info['is_checked'] == 1){
            $this->apiReturn(0,'状态有误');
        }

        //无偿服务无需支付
        if($need_info['type'] == 2){
            db()->startTrans();
            //修改状态
            if(!$apply_info->save(['is_checked' => 1])){
                db()->rollback();
                $this->apiReturn(0,'需求状态修改失败');
            }
            //添加消息通知
            if(!db('information')->insert([
                'user_id' => intval($this->post['apply_user']),
                'type' => 4,
                'content' => '需求-'.$need_info['title'].'申请通过',
                'add_time' => time()
            ])){
                db()->rollback();
                $this->apiReturn(0,'消息通知添加失败');
            }
            db()->commit();
            $this->apiReturn(1,'操作成功');

        }else{ //有偿服务，需要支付来确认是否报名成功
            if(!isset($this->post['pay_type'])){
                $this->apiReturn(0,'请选择支付方式');
            }
            //余额支付
            if(intval($this->post['pay_type']) == 0){
                if($this->user_info['balance'] < $need_info['pay_price']){
                    $this->apiReturn(0,'账户余额不足');
                }
                db()->startTrans();
                //修改发布者余额
                if(!db('user')->where('id',UID)->setDec('balance',$need_info['pay_price'])){
                    db()->rollback();
                    $this->apiReturn(0,'余额修改失败');
                }

                //被选中人信息
                $applyer = model('common/user')->getUserInfo(['id' => intval($this->post['apply_user'])],'grade_end_time,grade,from_city');

                //佣金
                if($applyer['grade'] == 0){
                    $yongjin = db('web_config')->where('key','p_yongjin')->value('value');
                }else{ //会员
                    $yongjin = db('web_config')->where('key','h_yongjin')->value('value');
                }

                $applyer_price = sprintf('%.2f',$need_info['pay_price']-$yongjin); //申请者所得金额

                if(!db('user')->where('id',intval($this->post['apply_user']))->setInc('balance',$applyer_price)){
                    db()->rollback();
                    $this->apiReturn(0,'余额修改失败1');
                }

                //交易明细
                $bill_count = db('bill')->insertAll([
                    [
                        'user_id' => UID,
                        'type' => 3,
                        'num' => $need_info['pay_price'],
                        'foreign_key' => $apply_info['id'],
                        'add_time' => time()
                    ],[
                        'user_id' => intval($this->post['apply_user']),
                        'type' => 4,
                        'num' => $applyer_price,
                        'foreign_key' => $apply_info['id'],
                        'add_time' => time()
                    ]
                ]);

                if(!$bill_count){
                    db()->rollback();
                    $this->apiReturn(0,'添加交易明细失败');
                }

                //信息
                $infor_count = db('information')->insertAll([
                    [
                        'user_id' => UID,
                        'type' => 3,
                        'content' => '需求-'.$need_info['title'].'支付成功',
                        'add_time' => time()
                    ],[
                        'user_id' => intval($this->post['apply_user']),
                        'type' => 4,
                        'content' => '需求-'.$need_info['title'].'申请通过',
                        'add_time' => time()
                    ]
                ]);

                if(!$infor_count){
                    db()->rollback();
                    $this->apiReturn(0,'信息添加失败');
                }

                if(!$apply_info->save([
                    'price' => $applyer_price,
                    'order_no' => date('YmdHis').rand(10000,99999),
                    'status' => 1,
                    'is_checked' => 1,
                    'pay_time' => time()
                ])){
                    db()->rollback();
                    $this->apiReturn(0,'状态修改失败');
                }

                //佣金处理
                if(!model('common/admin_bill')->addBill($applyer['from_city'],$yongjin,$apply_info['id'],1)){
                    db()->rollback();
                    $this->apiReturn(0,'操作失败，未知错误');
                }
               
                db()->commit();
                $this->apiReturn(1,'操作成功');
            }


            //微信支付
            if(intval($this->post['pay_type']) == 1){
                $options = [
                    'out_trade_no' => date('YmdHis').rand(10000,99999),
                    'total_fee' => $need_info['pay_price'] * 100,
                    'body' => '支付需求定金',
                    'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
                    'attach' => serialize(['attach' => 2,'apply_user' => intval($this->post['apply_user']),'id' => intval($this->post['id'])])
                ];

                $pay = new Pay(config('pay'));

                try{
                    $result = $pay->driver('wechat')->gateway('app')->apply($options);
                    $this->apiReturn(1,'微信支付信息',$result);
                } catch (Exception $e){
                    $this->apiReturn(0,$e->getMessage());

                }
            }

            //支付宝支付
            if(intval($this->post['pay_type']) == 2){
                $options = [
                    'out_trade_no' => date('YmdHis').rand(10000,99999),
                    'total_amount' =>  $need_info['pay_price'],
                    'subject' => '支付需求定金',
                    'passback_params' => UrlEncode(serialize(['passback_params' => 2,'apply_user' => intval($this->post['apply_user']),'id' => intval($this->post['id'])]))
                ];
                $pay = new Pay(config('pay'));
                try{
                    $result = $pay->driver('alipay')->gateway('app')->apply($options);
                    $this->apiReturn(1,'支付宝支付信息',$result);
                } catch (Exception $e){
                    $this->apiReturn(0,$e->getMessage());

                }
            }
        }
        
    }


}
